#include"ImageReceiver.h"
#include "src/common/log/log.h"
#include <QTimer>
#include <QDateTime>
#include <QDir>
#define  DogSN  "WLR0002"
#define  MaxImg 10*1024*1024
std::shared_ptr<CImageReceiver> CImageReceiver::m_InStance = nullptr;
std::once_flag CImageReceiver::m_flag;

std::shared_ptr<CImageReceiver>CImageReceiver::GetInStance(){
    std::call_once(m_flag, [](){
        m_InStance= std::shared_ptr<CImageReceiver>(new CImageReceiver(),
                                                [](CImageReceiver *ptr){delete ptr;});
    });
    return  m_InStance;
}

CImageReceiver::CImageReceiver(QObject *parent){
    m_connectionTimer = new QTimer(this);
    connect(this, &CImageReceiver::processData, this, &CImageReceiver::receivedImage);
    connect(m_connectionTimer, &QTimer::timeout, this, &CImageReceiver::createDirectory);//定时创建目录
    m_connectionTimer->start( 5*1000);
}
CImageReceiver::~CImageReceiver(){
}

void CImageReceiver::receivedImage(const QByteArray &data) {
    static bool receivingImage = false;
    static int imgSize = 0;
    static std::vector<uchar> m_imgData;
    std::string message = data.toStdString();
    if (message.find("start")== 0) {
        receivingImage = true;
        imgSize = std::stoi(message.substr(5));
        LOG_INFO(" receivedImage  imgSize: "<< imgSize);
        m_imgData.clear();
    }
    if (receivingImage && message != "END") {
        if(message.find("start")!=0){
            m_imgData.insert(m_imgData.end(), data.begin(), data.end());
        }
    }
    if (message == "END" && receivingImage ) {
        receivingImage = false;
        if (!m_imgData.empty()) {
            cv::Mat image = decodeImage(m_imgData);
            if (!image.empty()) {
              //  saveImage(image);
                emit SendDisplaySignal(image);
            } else {
                LOG_ERROR("Failed to decode image");
            }
        }

        m_imgData.clear();
        imgSize = 0;
    }
}

cv::Mat CImageReceiver::decodeImage(std::vector<uchar> &data)
{
    cv::Mat image;
    if (data.size() > 0 ) {
        try {
            image = cv::imdecode(data, cv::IMREAD_COLOR);
            if(image.empty()){
                LOG_ERROR("Error decoding image empty iamge size: " << data.size());
                return cv::Mat(); //返回一个空图像
            }else if (image.rows <= 0 || image.cols <=0){
                LOG_ERROR("Error decoding imager Invalid iamge size");
                image.release();
                return cv::Mat(); //返回一个空图像
            }
        } catch (const cv::Exception& ex) {
            LOG_ERROR("Error decoding image: " << ex.what());
            return cv::Mat();
        }
    }
    return image;
}
void CImageReceiver::saveImage(const cv::Mat &image){
    //save image
    QImage qImage(image.data, image.cols, image.rows, static_cast<int>(image.step), QImage::Format_BGR888);
    QString fileName = m_Path + "/" + QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch()) + ".jpg";
    LOG_INFO(" CImageReceiver::saveImage fileName: "  << fileName.toStdString());
    bool success = qImage.save(fileName, "JPG");
    if(success){
        LOG_INFO("Save Image Success: " << fileName.toStdString().c_str());
    }else{
        LOG_ERROR("Save image failed!" );
    }
}
void  CImageReceiver::createDirectory()
{
    static int TimeCount = 0;
    if (TimeCount ==  0){
        QString directoryName = getCurrentTime();
        QString path = QDir::currentPath() + "/" +  DogSN +"/RGB"+ "/" + directoryName;
        QDir dir(path);
        // 判断数据是否存在
        if(!dir.exists()){
            if(dir.mkpath(".")){
                LOG_INFO("CreateDir Path Succesful path:" << path.toStdString());
                m_Path = path;
            }else{
                LOG_ERROR("CreateDir Path Failed path:" << path.toStdString());
            }
        }
    }
    ++TimeCount;
    if(TimeCount >50)
    {
        TimeCount = 0; // 5分钟创建一次目录
    }
}
QString CImageReceiver::getCurrentTime()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    return currentTime.toString("yyyyMMddhhmmss");
}
